package com.example.demo.service.impl;

import com.example.demo.dao.IngredientsDao;
import com.example.demo.model.Ingredients;
import com.example.demo.service.IngredientService;
import com.example.demo.util.AIGenerateImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
import java.util.List;

@Service
public class IngredientServiceImpl implements IngredientService {

    @Autowired(required = false)
    private IngredientsDao ingredientsDao;

    @Override
    public byte[] generateImageFromIngredients(List<String> selectedIngredients) throws SQLException {
        // 调用 AI 图像生成器生成图片的逻辑，假设返回 Blob 对象
        AIGenerateImageUtil aiGenerateImageUtil = new AIGenerateImageUtil();
        Blob generatedImageBlob = aiGenerateImageUtil.callAIGenerateImageLogic(selectedIngredients);

        try (InputStream inputStream = generatedImageBlob.getBinaryStream();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        } catch (SQLException | IOException e) {
            // 处理异常
            e.printStackTrace();
            return new byte[0]; // 返回空数组或者抛出异常，视情况而定
        }
    }

    @Override
    public Ingredients getIngredientByName(String name) {
        return ingredientsDao.findByName(name);
    }
}

